package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();
        //TODO：【222024321072046/马云山]
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            handler = new DefaultHandler();
            //TODO：【222024321072046/马云山]
        }

        try {
            handler.handle(request, response);
        } catch (Exception e) {
            try {
                send500Error(response);
            } catch (IOException ex) {
                System.err.println("发送500错误失败: " + ex.getMessage());
            }
        }
    }

    private void send500Error(OutputStream response) throws IOException {
        PrintWriter writer = new PrintWriter(response);
        String content = "<h1>500 Internal Server Error</h1>";
        writer.println("HTTP/1.1 500 Internal Server Error");
        writer.println("Content-Type: text/html; charset=UTF-8");
        writer.println("Content-Length: " + content.getBytes().length);
        writer.println("Connection: close");
        writer.println();
        writer.println(content);
        writer.flush();
    }
}